import json
from django.utils import timezone
from django.contrib.auth.models import User
from .models import AuditLog


def get_client_ip(request):
    """
    获取客户端IP地址
    """
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


def log_admin_action(user=None, action='', resource='', resource_id='', 
                    ip_address='', user_agent='', request_data=None, 
                    response_data=None, status='success', error_message=''):
    """
    记录管理员操作日志
    
    Args:
        user: 执行操作的用户
        action: 操作类型
        resource: 操作的资源类型
        resource_id: 资源ID
        ip_address: 客户端IP地址
        user_agent: 用户代理
        request_data: 请求数据
        response_data: 响应数据
        status: 操作状态 (success/failed)
        error_message: 错误信息
    """
    try:
        # 序列化请求和响应数据
        request_data_json = None
        if request_data:
            try:
                request_data_json = json.dumps(request_data, ensure_ascii=False)
            except (TypeError, ValueError):
                request_data_json = str(request_data)
        
        response_data_json = None
        if response_data:
            try:
                response_data_json = json.dumps(response_data, ensure_ascii=False)
            except (TypeError, ValueError):
                response_data_json = str(response_data)
        
        # 创建审计日志记录
        AuditLog.objects.create(
            user=user,
            action=action,
            resource=resource,
            resource_id=resource_id,
            ip_address=ip_address,
            user_agent=user_agent,
            request_data=request_data_json,
            response_data=response_data_json,
            status=status,
            error_message=error_message,
            created_at=timezone.now()
        )
    except Exception as e:
        # 如果日志记录失败，不应该影响主要业务逻辑
        print(f"Failed to log admin action: {str(e)}")


def format_user_display_name(user):
    """
    格式化用户显示名称
    """
    if not user:
        return '未知用户'
    
    if user.first_name and user.last_name:
        return f"{user.first_name} {user.last_name}"
    elif user.first_name:
        return user.first_name
    elif user.last_name:
        return user.last_name
    else:
        return user.username


def validate_permission_code(permission_code):
    """
    验证权限代码格式
    权限代码格式：resource:action (例如: user:read, role:create)
    """
    if not permission_code or ':' not in permission_code:
        return False
    
    parts = permission_code.split(':')
    if len(parts) != 2:
        return False
    
    resource, action = parts
    if not resource or not action:
        return False
    
    # 验证资源和操作名称格式（只允许字母、数字和下划线）
    import re
    pattern = r'^[a-zA-Z0-9_]+$'
    return bool(re.match(pattern, resource)) and bool(re.match(pattern, action))


def generate_permission_code(resource, action):
    """
    生成权限代码
    """
    return f"{resource}:{action}"


def parse_permission_code(permission_code):
    """
    解析权限代码
    返回 (resource, action) 元组
    """
    if not validate_permission_code(permission_code):
        return None, None
    
    return permission_code.split(':', 1)


def check_password_strength(password):
    """
    检查密码强度
    返回 (is_strong, message)
    """
    if len(password) < 8:
        return False, "密码长度至少8位"
    
    import re
    
    # 检查是否包含大写字母
    if not re.search(r'[A-Z]', password):
        return False, "密码必须包含至少一个大写字母"
    
    # 检查是否包含小写字母
    if not re.search(r'[a-z]', password):
        return False, "密码必须包含至少一个小写字母"
    
    # 检查是否包含数字
    if not re.search(r'\d', password):
        return False, "密码必须包含至少一个数字"
    
    # 检查是否包含特殊字符
    if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
        return False, "密码必须包含至少一个特殊字符"
    
    return True, "密码强度符合要求"


def sanitize_user_input(input_data):
    """
    清理用户输入数据，防止XSS攻击
    """
    if isinstance(input_data, str):
        # 移除潜在的危险字符
        import html
        return html.escape(input_data)
    elif isinstance(input_data, dict):
        return {key: sanitize_user_input(value) for key, value in input_data.items()}
    elif isinstance(input_data, list):
        return [sanitize_user_input(item) for item in input_data]
    else:
        return input_data


def generate_audit_summary(start_date=None, end_date=None):
    """
    生成审计日志摘要
    """
    from django.db.models import Count
    
    queryset = AuditLog.objects.all()
    
    if start_date:
        queryset = queryset.filter(created_at__gte=start_date)
    if end_date:
        queryset = queryset.filter(created_at__lte=end_date)
    
    # 按操作类型统计
    action_stats = queryset.values('action').annotate(count=Count('id')).order_by('-count')
    
    # 按状态统计
    status_stats = queryset.values('status').annotate(count=Count('id'))
    
    # 按用户统计
    user_stats = queryset.values('user__username').annotate(count=Count('id')).order_by('-count')[:10]
    
    # 按资源类型统计
    resource_stats = queryset.values('resource').annotate(count=Count('id')).order_by('-count')
    
    return {
        'total_logs': queryset.count(),
        'action_stats': list(action_stats),
        'status_stats': list(status_stats),
        'user_stats': list(user_stats),
        'resource_stats': list(resource_stats)
    }